<template>
  <div>
    <customDialog
      :title="`${title}推广链接`"
      :dialogVisible="dialogVisible"
      @close="closeDialog"
      @confirm="confirmDialog(ruleFormRef)"
      width="60%"
    >
      <div>
        <el-form
          ref="ruleFormRef"
          :model="formData"
          :rules="rules"
          label-width="110px"
        >
          <el-form-item label="名称" prop="linkName" style="width: 70%">
            <el-input
              v-model="formData.linkName"
              clearable
              maxlength="50"
              show-word-limit
            />
            <span class="grey">给推广链接起个名字，方便查找</span>
          </el-form-item>
          <el-form-item label="推广剧集" prop="operaId">
            <el-select
              v-model="formData.operaId"
              placeholder="请选择"
              clearable
              @change="changeOptions"
              :disabled="title == '编辑'"
            >
              <el-option
                v-for="(item, index) in optionEpisode"
                :key="index"
                :label="item.text"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="推广集数" prop="episode">
            <span v-if="!formData.operaId">请先选择推广剧集</span>
            <el-select
              v-model="formData.episode"
              placeholder="请选择"
              filterable
              clearable
              v-else
            >
              <el-option
                v-for="(item, index) in optionCount"
                :key="index"
                :label="item.text"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="推广平台" prop="platform">
            <el-select
              v-model="formData.platform"
              placeholder="请选择"
              :disabled="title == '编辑'"
            >
              <el-option
                v-for="(item, index) in optionPlatform"
                :key="index"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="卡点预览秒数" prop="previewSeconds">
            <el-input-number v-model="formData.previewSeconds" :min="0" />
          </el-form-item> -->
        </el-form>
      </div>
    </customDialog>
  </div>
</template>

<script lang="ts" setup>
import customDialog from "@/components/CustomDialog/index.vue";
import { ref, reactive, toRefs, onMounted, computed } from "vue";
import type { FormInstance } from "element-plus";
import {
  promotionsAdd,
  promotionsEdit,
  operasOptions,
  operasNums,
} from "@/api/promotionLink/index";
import { ModelOptins } from "@/api/promotionLink/types";
import { useUserStore } from "@/store/modules/user";
import { cloneDeep } from "lodash-es";

const user = useUserStore().user;
const ruleFormRef = ref<FormInstance>();
const dialogVisible = ref(false);
const title = ref<string>("");
const form = {
  id: undefined,
  linkName: "",
  operaId: "",
  episode: "",
  platform: "tt2",
  // previewSeconds: 0,
};
const formData = ref(Object.assign({}, form));

// 剧集
const optionEpisode = ref<Array<ModelOptins>>([]);

const optionCount = ref<Array<any>>([]);

const optionPlatform = ref([
  { label: "巨量 2.0", value: "tt2" },
  { label: "星图", value: "xt", disabled: user.userAppObj?.appType === "wx" },
]);

const rules = reactive({
  linkName: [{ required: true, message: "请输入名称", trigger: "blur" }],
  operaId: [{ required: true, message: "请选择剧集", trigger: "change" }],
  episode: [{ required: true, message: "请选择集数", trigger: "change" }],
  platform: [{ required: true, message: "请选择推广平台", trigger: "change" }],
});

// 关闭 重置
const closeDialog = () => {
  Object.assign(formData.value, form);
  dialogVisible.value = false;
};

// 成功
const emit = defineEmits(["success"]);
const confirmDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      let URL;
      if (title.value === "编辑") {
        URL = promotionsEdit;
      } else {
        URL = promotionsAdd;
      }
      // formData.value.previewSeconds = formData.value?.previewSeconds || 0;
      URL(formData.value).then(() => {
        ElMessage.success(`${title.value}成功`);
        dialogVisible.value = false;
        closeDialog();
        emit("success");
      });
    }
  });
};

// 获取剧集选项
const getOperasOptions = () => {
  operasOptions({}).then((res: any) => {
    optionEpisode.value = res;
  });
};

// 改变剧集
const changeOptions = (data: number) => {
  // 重置剧集集数
  optionCount.value = [];
  operasNums(data).then((res: any) => {
    handleOperas(res?.updateEpisodeNo);
  });
};

// 处理剧集集数
const handleOperas = (data: number) => {
  for (let i = 0; i <= data; i++) {
    if (i < data) {
      let flag = {
        text: `第${i + 1}集`,
        value: i + 1,
      };
      optionCount.value.push(flag);
    }
  }
};

// 父级电子显示dialog
const showDialog = (val: Record<string, any>) => {
  // console.log("剧集新增编辑弹窗显示---", val);
  title.value = val ? "编辑" : "新增";
  dialogVisible.value = true;
  if (title.value == "编辑") {
    formData.value = cloneDeep(val);
    changeOptions(val.operaId);
  }
  getOperasOptions();
};

defineExpose({
  showDialog,
});
</script>

<style scoped lang="scss"></style>
